import hashlib

from django.core.exceptions import ValidationError
from django import forms
from django.shortcuts import render, HttpResponse, redirect, reverse

from app01 import models


# 封装init
class BSForm(forms.ModelForm):
    """
    拥有bootstrap样式
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 自定义操作
        for field in self.fields.values():
            field.widget.attrs["class"] = "form-control"  # 给每一个form表单添加一个 class字段


class RegForm(forms.ModelForm):
    # username = forms.CharField()
    password = forms.CharField(error_messages={"required": "这是必选项"},
                               widget=forms.PasswordInput(attrs={"placeholder": "密码", "type": "password"}), label="密码",
                               min_length=6)  # 因为我们这里重新写了字段，所以我们重新定义了报错的默认信息
    re_pwd = forms.CharField(widget=forms.PasswordInput(attrs={"placeholder": "确认密码", "type": "password"}),
                             label="确认密码", min_length=6)

    # 获取和设置所有的字段
    class Meta:
        model = models.User  # 获取整个user表
        # fields = ["username","password"] # 获取自定义的models的字段
        fields = "__all__"  # 获取所有的字段
        exclude = ['last_time']  # 取消那些字段
        # labels = {  # 给选中的字段重命名
        #     "username":"用户名",
        # }

        widgets = {  # 改对应字段的input框的格式
            "username": forms.TextInput(attrs={"placeholder": "用户名", "autocomplete": "off"}),
            "position": forms.TextInput(attrs={"placeholder": "职位"}),
            # "company":forms.Select(),
            "phone": forms.TextInput(attrs={"placeholder": "电话"}),
        }
        error_messages = {  # 修改每个字段默认的报错信息
            "username": {
                "required": "必填项"
            }
        }

    # 局部钩子 手机号
    def clean_phone(self):
        import re
        phone = self.cleaned_data.get("phone")  # 获取phone字段，用户输入的内容
        if re.match(r'^1[3-9]\d{9}$', phone):
            return phone
        raise ValidationError("手机号格式不正确")

    # 全局钩子 两次输入密码的一致性
    def clean(self):
        self._validate_unique = True  # 数据库校验唯一
        password = self.cleaned_data.get("password", " ")
        re_pwd = self.cleaned_data.get("re_pwd")
        if password == re_pwd:
            # 给密码加密
            md5 = hashlib.md5()
            md5.update(password.encode("utf-8"))
            self.cleaned_data["password"] = md5.hexdigest()  # 把加密的密码，重新给password
            return self.cleaned_data  # 就返回全部的数据
        self.add_error("re_pwd", "两次密码不一致！！")  # 给对应的字段后面添加错误信息
        raise ValidationError("两次密码不一致")

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 自定义操作
        field = self.fields["company"]  # 获取到company的值

        choices = field.choices
        choices[0] = ("", "选择公司")
        field.choices = choices  # 把修改的值在传递给它


# 文章新增form
class ArticleForm(forms.ModelForm):
    class Meta:
        model = models.Article  # 获取Article所有的字段
        fields = "__all__"
        exclude = ["detail"]
        # widgets={
        #     "title":forms.IntegerField(attrs={"class":"form-control"})
        # }

    def __str__(self):
        return self.name

    # 方法一
    def __init__(self, request, *args, **kwargs):
        # 获取到用户传来的其他的参数 request 不要往下面的__init__传了
        super().__init__(*args, **kwargs)

        # 自定义操作
        field = self.fields["author"]  # 获取到company的值

        print(field)

        field1 = self.fields["category"]  # 获取到company的值
        print(field1)

        # 自定义操作
        for field in self.fields.values():
            field.widget.attrs["class"] = "form-control"  # 给每一个form表单添加一个 class字段

        # 修改choices的参数
        print(list(self.fields["author"].choices))
        self.fields["author"].choices = [(request.user_obj.pk, request.user_obj.username)]  # 当前的pk 和作者


class ArticleDetailForm(forms.ModelForm):
    class Meta:
        model = models.ArticleDetail  # 获取Article所有的字段
        fields = "__all__"
        exclude = ["detail"]


# 分类的modelform
class CategoryForm(BSForm):
    class Meta:
        model = models.Category
        fields = "__all__"


class SeriesForm(BSForm):
    class Meta:
        model = models.Series
        fields = "__all__"
